import random
import win32api
import requests
import json,threading
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from datetime import datetime
def get_user_agent():
    # 各种PC端
    user_agent_two = [
        
        # Opera
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60",
        "Opera/8.0 (Windows NT 5.1; U; en)",
        "Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50",
        # Firefox
        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0",
        "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
        # Safari
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2",
        # chrome
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gnavigator.webdriverecko) Chrome/39.0.2171.71 Safari/537.36",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
        "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
        # 360
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36",
        "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
        # 淘宝浏览器
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
        
        # 猎豹浏览器
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
        # QQ浏览器
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
        # sogou浏览器
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)",
        # maxthon浏览器
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36",
        # UC浏览器
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36",
    ]
    # 各种移动端
    user_agent_three = [
        "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Mobile Safari/537.36",
        "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.8552.1083 Mobile Safari/537.36",
        "Mozilla/5.0 (Linux; Android 8.1.0; vivo Y85 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/8.0.10.1",
        "Mozilla/5.0 (Linux; U; Android 9; zh-cn; STF-AL00 Build/HUAWEISTF-AL00) AppleWebKit/534.30 (KHTML,like Gecko) Version/4.0 Mobile Safari/534.30",
        "Mozilla/5.0 (Linux; U; Android 4.4.4; zh-CN; Coolpad Y82-520 Build/KTU84P) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/10.9.8.738 U3/0.8.0 Mobile Safari/534.30",
        "Mozilla/5.0 (Linux; U; Android 5.1; zh-cn; KONKA D1 Build/LMY47D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.100 U3/0.8.0 Mobile Safari/534.30 Tanggula/0.1.0 WebLight/1.4.1 oc_AppSearch/3.3.7.or",
        "Mozilla/5.0 (Linux; U; Android 5.1; zh-cn; Bestsonny_LT989 Build/LMY47D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.100 U3/0.8.0 Mobile Safari/534.30 Tanggula/0.1.0 WebLight/1.4.1 oc_AppSearch/3.5.1.fb",
        "Mozilla/5.0 (Linux; U; Android 10; zh-cn; STK-AL00 Build/HUAWEISTK-AL00) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.6 Mobile Safari/537.36",
        "Mozilla/5.0 (Linux; Android 8.1.0; vivo X9s Plus Build/OPM1.171019.019; wv) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36 VivoBrowser/8.1.14.2",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/17F80 UCBrowser/13.0.6.1350 Mobile  AliApp(TUnionSDK/0.1.20.3)",
        "Mozilla/5.0 (Linux; U; Android 6.0.1; zh-cn; MI 5 Build/MXB48T) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.146 Mobile Safari/537.36 XiaoMi/MiuiBrowser/8.8.7",
        "Mozilla/5.0 (Linux; Android 10; ELE-AL00 Build/HUAWEIELE-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.99 Mobile Safari/537.36",
        "Mozilla/5.0 (iPhone 6; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 MQQBrowser/7.4 Mobile/14B100 Safari/8536.25 MttCustomUA/2 QBWebViewType/1 WKType/1",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X; zh-CN) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/17F80 UCBrowser/12.4.7.1178 Mobile  AliApp(TUnionSDK/0.1.20.3)",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 MQQBrowser/10.4.0 Mobile/15E148 Safari/604.1 QBWebViewUA/2 QBWebViewType/1 WKType/1",
        # IPhone
        "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        # IPod
        "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        # IPAD
        "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
        "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        # Android
        "Mozilla/5.0 (Linux; U; Android 2.2.1; zh-cn; HTC_Wildfire_A3333 Build/FRG83D) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        # QQ浏览器 Android版本
        "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        # Android Opera Mobile
        "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
        # Android Pad Moto Xoom
        "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
        # BlackBerry
        "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
        # WebOS HP Touchpad
        "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
        # Nokia N97
        "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
        # Windows Phone Mango
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
        # UC浏览器
        "UCWEB7.0.2.37/28/999",
        "NOKIA5700/ UCWEB7.0.2.37/28/999",
        # UCOpenwave
        "Openwave/ UCWEB7.0.2.37/28/999",
        # UC Opera
        "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999"
    ]
   
    user_agent_set = user_agent_one + user_agent_two + user_agent_three
    user_agent = random.choice(user_agent_two)
    return user_agent
#屏幕分辨率设置
def setDisplay():
    display_size = [
        [1920,1080],
        [1680,1200],
        [1680,1050],
        [1600,900],
        [1440,900],
        [1400,1050],
        [1366,768],
        [1280,960],
        [1280,720],
        [1080,960],
        [1024,768],
        [960,720]
    ]
    d_size = random.choice(display_size)
    dm = win32api.EnumDisplaySettings(None, 0)
    dm.PelsWidth = d_size[0]
    dm.PelsHeight = d_size[1]
    dm.BitsPerPel = 32
    dm.DisplayFixedOutput = 0
    win32api.ChangeDisplaySettings(dm, 0)

def start1():
    setDisplay()
    dailiip = requests.get('http://dps.kdlapi.com/api/getdps/?orderid=999617741662079&num=1&pt=1&sep=1')
    options = webdriver.ChromeOptions()
    options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
    # options.add_argument('--headless')
    # 设置代理
    options.add_argument("--proxy-server=%s" % dailiip.text)
    # 此步骤很重要，设置为开发者模式，防止被各大网站识别出来使用了Selenium
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_experimental_option('useAutomationExtension', False)
    # 后面是你的浏览器驱动位置，记得前面加r'','r'是防止字符转义的
    driver = webdriver.Chrome(r'C:\Users\Administrator\AppData\Local\Programs\Python\Python38\chromedriver.exe',options=options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """
                Object.defineProperty(navigator, 'webdriver', {
                get: () => undefined
                })
            """
            })
    driver.maximize_window()
    driver.implicitly_wait(45)
    sleep(1)
    # 用get打开百度页面
    driver.get("https://www.baidu.com")
    sleep(random.randint(5, 10))

    try:
        scrollnum = [200,200,100,300]
        keywords = ['青岛-网站制作','青岛-网站制作-公司','青岛-网站建设','青岛-网站建设-公司','青岛-网站-制作','青岛网站-制作公司','青岛网站-建设','青岛网站建设-公司','青岛做网站']
        for i in range(1):

            rand1 = random.randint(0,len(keywords)-1)
            searchsword = keywords[rand1]
            searchstr = searchsword.split('-')
            for i1 in searchstr:
                sleep(random.randint(1, 3))
                driver.find_element_by_id('kw').send_keys(i1)
            # sleep(2)
            # bdinput = driver.find_element_by_id('kw').send_keys('制作')
            # sleep(1)
            # bdinput = driver.find_element_by_id('kw').send_keys('公司')
            # sleep(1)
            try:
                idsu = driver.find_element_by_id('su')
                ActionChains(driver).move_to_element(idsu).perform()
                idsu.click()
                sleep(random.randint(5, 8))
                idtool = driver.find_elements_by_class_name("search_tool")[0]
                ActionChains(driver).move_to_element(idtool).perform()
                idtool.click()
                sleep(random.randint(1, 5))
                idtoolsi = driver.find_elements_by_class_name("search_tool_si")[0]
                ActionChains(driver).move_to_element(idtoolsi).perform()
                idtoolsi.click()
                sleep(random.randint(1, 5))
                driver.find_element_by_xpath("//input[@name=\"si\"]").send_keys('www.yujianlong.com')
                sleep(random.randint(5, 10))
                idsubmit = driver.find_elements_by_class_name("c-tip-timerfilter-si-submit")[0]
                ActionChains(driver).move_to_element(idsubmit).perform()
                idsubmit.click()
                sleep(random.randint(3,8))
                a = 0
            except Exception as e:
                driver.delete_all_cookies()
                print('error-yanzhengma')
                pass
            rand2 = random.randint(1,4)
            SEMS = driver.find_elements_by_xpath('//*[@id]/div[3]/a/span') #竞价
            for sem in SEMS:
                rd1 = random.randint(1, 8)
                if rd1==2 or rd1==3:
                    sem.click()
                    sleep(random.randint(3, 15))
            try:
                for i in driver.find_elements_by_class_name("c-showurl"):
                    if i.text.find('www.yujianlong.com') != -1:
                        sleep(random.randint(1, 3))
                        if a==0:
                            try:
                                i.click()
                                wins = driver.window_handles
                                sleep(random.randint(5, 25))
                                driver.switch_to.window(wins[0])
                                n_date = datetime.now()
                                n_date = n_date.strftime("%H:%M:%S")
                                print(n_date)
                                print('success')
                            except Exception as e:
                                pass
                        elif a==rand2:  
                            try:
                                scrolljs = 'window.scrollTo(0, %s)' % (scrollnum[random.randint(0, 3)])
                                driver.execute_script(scrolljs)
                                sleep(random.randint(3, 8))
                                i.click()  
                                sleep(random.randint(5, 15))
                            except Exception as e:
                                pass
                        a+=1
            except Exception as e:
                driver.delete_all_cookies()
                print('error-showurl')
                # driver.quit()         
            bdinput = driver.find_element_by_id('kw').clear()
        driver.delete_all_cookies()
        # 关闭浏览器
        driver.quit()
    except Exception as e:
        driver.delete_all_cookies()
        print ("YuTest", format(e))
        driver.quit()

def run_web():
    th1 = threading.Thread(target=start1)
    th1.start()
    return 0

while True:
    try:
        run_web()
        format_pattern = "%H:%M:%S"
            
        end_date = datetime.now()
        end_date = end_date.strftime(format_pattern)
        end_date = datetime.strptime(end_date, format_pattern)
        # 将 'datetime.datetime' 类型时间通过格式化模式转换为 'str' 时间
        if   end_date > datetime.strptime('11:00:00', format_pattern) and end_date < datetime.strptime('13:00:00', format_pattern) :
            sleep(random.randint(600, 1800))
        elif end_date > datetime.strptime('17:00:00', format_pattern) and end_date < datetime.strptime('21:00:00', format_pattern) :
            sleep(random.randint(600, 1800))
        elif end_date > datetime.strptime('21:00:00', format_pattern) and end_date < datetime.strptime('23:59:00', format_pattern) :
            sleep(random.randint(1800, 3600))
        elif end_date > datetime.strptime('00:00:00', format_pattern) and end_date < datetime.strptime('06:00:00', format_pattern) :
            sleep(random.randint(1800, 3600))
        else:
            sleep(random.randint(600, 1800))
    except Exception as e:
        pass
